const express = require("express");
const router = express.Router();
const { db, genid } = require("../db/DbUtils");
const { jwtCheak } = require("../utils/jwt");

// 查询
router.get("/category", async (req, res) => {
  const search_sql = "SELECT * FROM `category`";
  let { err, rows } = await db.async.all(search_sql, []);
  if (!err) {
    res.send({
      code: 200,
      msg: "查询成功",
      data: rows,
    });
  } else {
    res.send({
      code: 500,
      msg: "查询失败",
    });
  }
});

// 添加
/**
 * params
 *   name  分类名称
 *  */
router.post("/category", jwtCheak, async (req, res) => {
  // let { token } = req.headers;
  // let admin_sql = "SELECT * FROM `admin` WHERE `token` = ?";
  // let adminRes = await db.async.all(admin_sql, [token]);
  // if (adminRes.err || adminRes.rows.length === 0) {
  //   res.send({
  //     code: 403,
  //     msg: "未登录",
  //   });
  //   return;
  // }

  let { name } = req.body;
  const insert_sql = "INSERT INTO `category` (`id`, `name`) VALUES (?,?)";
  let { err, rows } = await db.async.run(insert_sql, [genid.NextId(), name]);
  if (!err) {
    res.send({
      code: 200,
      msg: "添加成功",
    });
  } else {
    res.send({
      code: 500,
      msg: "添加失败",
    });
  }
});

// 修改
/**
 * params
 *   id   要修改的分类id
 *   name 要修改的新名称
 *  */
router.put("/category", jwtCheak, async (req, res) => {
  let { id, name } = req.body;
  const update_sql = "UPDATE `category` SET `name` = ? WHERE `id` = ?";
  let { err, rows } = await db.async.run(update_sql, [name, id]);
  if (!err) {
    res.send({
      code: 200,
      msg: "修改成功",
    });
  } else {
    res.send({
      code: 500,
      msg: "修改失败",
    });
  }
});

// 删除  /categoey?id=xxx
/**
 * params
 *   id   要删除分类的id
 *  */
router.delete("/category", jwtCheak, async (req, res) => {
  let id = req.query.id;
  const delete_sql = "DELETE FROM `category` WHERE `id` = ?";
  let { err, rows } = await db.async.run(delete_sql, [id]);
  if (!err) {
    res.send({
      code: 200,
      msg: "删除成功",
    });
  } else {
    res.send({
      code: 500,
      msg: "删除失败",
    });
  }
});

module.exports = router;
